package com.lucenten.collect.gnss.handler.impl;

import cn.quevo.common.file.FileUtils;
import cn.quevo.common.lang.NumberUtils;
import cn.quevo.common.lang.StringUtils;
import com.lucenten.collect.gnss.entity.GnssFile;
import com.lucenten.collect.gnss.entity.SatelliteStation;
import com.lucenten.collect.gnss.enums.GnssFormat;
import com.lucenten.collect.gnss.handler.AbstractGnssHandler;
import com.lucenten.collect.gnss.handler.GnssHandler;
import com.lucenten.collect.gnss.service.ObsErvationService;
import com.lucenten.collect.gnss.service.SatelliteStationService;
import com.lucenten.mq.SendJmsInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * 第四步：.文件重命名
 */
@Slf4j
public class ReNameGnssHandler extends AbstractGnssHandler implements GnssHandler {


    public ReNameGnssHandler(SatelliteStationService satelliteStationService, ObsErvationService obsErvationService) {
        super(satelliteStationService, obsErvationService);
    }

    @Override
    protected boolean doProcess(GnssFile gnssFile) {
        // 如果没有需要重命名的，则直接忽略
        if (StringUtils.isEmpty(gnssFile.getStorageStations())) {
            return true;
        }
        String root = super.getDataFormatPath(GnssFormat.RINEX, gnssFile);
        Path file = null;
        SatelliteStation station = null;
        for (Map.Entry<String, SatelliteStation> entry : gnssFile.getStorageStations().entrySet()) {
            station = entry.getValue();
            // 如果更改之前和更改之后的站点名称一致，则无需更改
            if (station.getStationName().equalsIgnoreCase(station.getReStationName())) {
                continue;
            }
            for (String suffix : FILE_NAMES) {
                file = Paths.get(root,gnssFile.getDayOfYearPath(),getFileName(suffix, station, gnssFile));
                if (Files.notExists(file)) {
                    continue;
                }
                FileUtils.move(file,Paths.get(root,gnssFile.getDayOfYearPath(),super.getNewStationName(file.getFileName().normalize().toString(),station.getReStationName())));
//                SendJmsInfo.sendGnssMq(11, file.getFileName().normalize().toString(), 0);
            }
        }
        return true;
    }

    /**
     * 获取文件名称
     *
     * @param suffix
     * @param station
     * @param gnssFile
     * @return
     */
    private String getFileName(String suffix, SatelliteStation station, GnssFile gnssFile) {
        return station.getStationName() + NumberUtils.format( gnssFile.getDayOfYear(),"000") +  NumberUtils.format( gnssFile.getHoure(),"00") + "." + gnssFile.getYear().toString().substring(2) + suffix;
    }

}
